package com.example.saiweisi.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/file")
@RestController
@CrossOrigin
@Slf4j
public class FileController {


    @Value("${files.upload.path}")
    private String fileUploadPath;

    /**
     * 文件上传接口
     *
     * @param file 前端传过来的文件
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        //name 为文件的后缀名
        String name = FileUtil.extName(filename);
        //先存储到本地
        File uploadParentFile = new File(fileUploadPath);
        //判断文件目录是否存在，不存在就创建
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        //定义一个唯一的文件名
        String uuid = IdUtil.fastSimpleUUID();
        String finalName = uuid + StrUtil.DOT + name;
        //生成保存的路径和文件名
        File uploadFile = new File(fileUploadPath + uuid + StrUtil.DOT + name);
        //把获取到的文件存到本地中
        file.transferTo(uploadFile);

        //获取文件的url
        String url = "http://localhost:8081/file/" + finalName;
        return url;
    }

    @PostMapping("/tinymce/upload")
    public Map<String, String> tinymceUpload(@RequestParam MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        //name 为文件的后缀名
        String name = FileUtil.extName(filename);
        //先存储到本地
        File uploadParentFile = new File(fileUploadPath);
        //判断文件目录是否存在，不存在就创建
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        //定义一个唯一的文件名
        String uuid = IdUtil.fastSimpleUUID();
        String finalName = uuid + StrUtil.DOT + name;
        //生成保存的路径和文件名
        File uploadFile = new File(fileUploadPath + uuid + StrUtil.DOT + name);
        //把获取到的文件存到本地中
        file.transferTo(uploadFile);

        //获取文件的url
        String url = "http://localhost:8081/file/" + finalName;
        HashMap<String, String> map = new HashMap<>();
        map.put("location", url);
        return map;
    }
}
